package ua.kpi_java_training.zabrodskyi.module3;

/**
 * The class imitates life course in environment.
 * 
 * @author Maksym Zabrodskyi
 * @version 25-Jun-2013
 */
public class Life {

	/**
	 * The life expectancy value (quantity of life cycles).
	 */
	private int lengthLife;

	/**
	 * Creates a new life in environment.
	 * 
	 * @param lengthLife
	 *            - quantity of life cycles, should be more zero.
	 */
	public Life(int lengthLife) {
		if (lengthLife <= 0) {
			throw new RuntimeException(
					"Error: incorrect value of length of life = " + lengthLife);
		}
		this.lengthLife = lengthLife;
	}

	/**
	 * Starts life cycles in environment.
	 * 
	 * @param environment
	 *            - environment in which the life is modeled.
	 */
	public void run(Environment environment) {
		for (int time = 1; time <= lengthLife; time++) {
			addThisCycleToStatistics(time);
			doOneLifeCycle(environment);
		}
	}

	/**
	 * Does one life cycle.
	 * 
	 * @param environment
	 *            - environment in which the life is modeled.
	 */
	private void doOneLifeCycle(Environment environment) {
		for (int index = 0; index < environment.getSize(); index++) {
			if (!environment.isFreeCell(index)
					&& (ElementType.PREDATOR.equals(environment.getElement(
							index).getType()) || ElementType.VICTIM
							.equals(environment.getElement(index).getType()))) {
				Animal animal = (Animal) environment.getElement(index);
				animal.move(environment);
				animal.eat(environment);
				animal.spawn(environment);
				Statistics.addMessage(animal.toString());
			}
		}
	}

	/**
	 * Adds the message about this life cycle in statistics.
	 * 
	 * @param time
	 *            - number of current life cycle.
	 */
	private void addThisCycleToStatistics(int time) {
		String dash = String.format("%0" + 15 + "d", 0).replace("0", "= ");
		Statistics.addMessage(dash + "Life cycle = " + time);
	}

	/**
	 * Converts a copy of this class to a string format.
	 */
	@Override
	public String toString() {
		return String.format("Life goes %s times", lengthLife);
	}

}
